import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {message} from 'antd';
let initState={
    list:{},
    teacher_list_origin:[], //教师列表的原始数据
    teacher_list:[], //教师列表在table上显示的数据
    loading:false //数据的加载状态 默认是非加载中
}
let reducer=(state=initState,actions)=>{
   let  newState=JSON.parse(JSON.stringify(state));
   switch(actions.type){
       case "SET_LIST":
        newState.list=actions.data;
        return newState;


        // 设置加载状态
        case "SET_LOADING":
        console.log('set loading',actions.data)
        newState.loading=actions.data;
        return newState;
        

        // 教师操作
        // 设置教师列表
        case "SET_TEACHER_LIST":
        newState.teacher_list_origin=actions.data;
        newState.teacher_list=actions.data;
        return newState;

        // 教师搜索
        case "SEARCH_TEACHER":
        console.log('search teacher',actions.data);
        // 恢复原始数据  在原始数据的基础上进行搜索
        newState.teacher_list=[...newState.teacher_list_origin];
        newState.teacher_list=newState.teacher_list.filter((item)=>item.name.includes(actions.data));
    
        return newState;

        // 添加教师
        case "ADD_TEACHER":    
        actions.data.id=new Date().getTime();// 生成id 随机数

        // 检测数据
        if(!actions.data.age){
            actions.data.age=20;  // 设置年龄默认值
        }
         
        
        if(!actions.data.clzss){
            actions.data.clzss=""; // 设置默认带班值
        }

        if(!actions.data.year){
            actions.data.year="2020"; //设置默认入职年份
        }
        if(!actions.data.image){
            actions.data.image="https://dummyimage.com/100X100/f279a9&text=没有头像" ;  //设置默认头像
        }
        newState.teacher_list.unshift(actions.data);
        newState.teacher_list_origin=newState.teacher_list;
        return newState;

        // 删除教师
        case "DEL_TEACHER":
        let index=newState.teacher_list.findIndex((item)=>item.id+""===actions.data.id+"");
        if(index>=0){
            newState.teacher_list.splice(index,1);
            message.success("成功删除教师" + actions.data.name);
        }
        return newState;
           default:
               return state;

   }
}
export default createStore(reducer,applyMiddleware(thunk));